package cn.itsource.system.service.impl;

import cn.itsource.system.domain.Role;
import cn.itsource.system.mapper.MenuMapper;
import cn.itsource.system.mapper.PermissionMapper;
import cn.itsource.system.mapper.RoleMapper;
import cn.itsource.system.service.IRoleService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public void add(Role role) {
        roleMapper.add(role);
        //先添加中间表
        initRelationTable(role);

    }

    @Override
    public void delete(Long id) {
        roleMapper.delRolePermissions(id);
        roleMapper.delRoleMenus(id);
        roleMapper.delRoleEmployee(id);
        roleMapper.delete(id);
    }

    @Override
    public void update(Role role) {
        //删除中间表信息
        roleMapper.delRolePermissions(role.getId());
        roleMapper.delRoleMenus(role.getId());
        initRelationTable(role);
    }

    @Override
    public void batchDelete(List<Long> ids) {
        for (Long id : ids) {
            delete(id);
        }
    }

    private void initRelationTable(Role role) {
        Long roleId = role.getId();
        //角色分配权限
        List<Long> permissions = role.getPermissions();
        if(permissions.size() > 0){
            roleMapper.addRolePermissons(role);
        }

        //角色分配菜单
        List<Long> menus = role.getMenus();
        if(menus.size() > 0) {
            roleMapper.addRoleMenus(role);
        }
    }
}
